/* eslint-disable no-unused-vars */
/* eslint-disable import/order */
import { AnyAction } from 'redux';
import { VALIDATE, LOGOUT, CHANGE_AVATAR } from '../action-types';
import { validate, login, register } from '@/api/profile';
import { RegisterPayload, RegisterResult, LoginPayload, LoginResult } from '@/typings/user';
import { push } from 'connected-react-router';
import { message } from 'antd';

export default {
    validate(): AnyAction {
        return {
            type: VALIDATE,
            payload: validate()
        };
    },
    login(params: LoginPayload) {
        return function (dispatch: any) {
            (async function () {
                try {
                    const result: LoginResult = await login<LoginResult>(params);
                    if (result.success) {
                        sessionStorage.setItem('access_token', result.data.token);
                        dispatch(push('/profile'));
                    } else {
                        message.error(result.message);
                    }
                } catch (error) {
                    message.error('登录失败');
                }
            })();
        };
    },
    register(params: RegisterPayload) {
        return function (dispatch: any) {
            (async function () {
                try {
                    const result:RegisterResult = await register<RegisterResult>(params);
                    if (result.success) {
                        dispatch(push('/login'));
                    } else {
                        message.error(result.message);
                    }
                } catch (error) {
                    message.error('注册失败');
                }
            })();
        };
    },
    logout() {
        return function (dispatch: any) {
            sessionStorage.removeItem('access_token');
            dispatch({ type: LOGOUT });
            dispatch(push('/login'));
        };
    },
    changeAvatar(avatar: string) {
        return {
            type: CHANGE_AVATAR,
            payload: avatar
        };
    }
};
